package com.mq.exchange;

import com.mq.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RecvExchange2 {
//同一交换机 短信队列 收的到
    private static final String QUEUE_NAME="015_queue_fanout_sms";
    private static final String EXCHANGE_NAME = "java015_exchange_test1";

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtils.getConnection();

        final Channel channel = connection.createChannel();

        //队列声明
        channel.queueDeclare(QUEUE_NAME,true,false,false,null);

        //绑定队列到交换机转发器
        channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"");

        /**
         * 保证一次只分发一个
         */
        channel.basicQos(1);

        //定义队列的消费者
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
                    throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("[2] recv msg" + message);

                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    System.out.println("[2] done");

                    // 手动回执
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            }
        };
        boolean autoAck = false;  //自动应答

        channel.basicConsume(QUEUE_NAME, autoAck, consumer);
    }
}